﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace LightSwitchApplication
{
    public partial class ApplicationDataService
    {
        /// <summary>
        /// This method is still needed, because of the init functions.
        /// Due to Property IsReady it should be skippable. So, refactoring is needed. -.-
        /// </summary>
        /// <param name="entity"></param>
        partial void tbServerJobSet_Inserted(tbServerJob entity)
        {
            UserCode.ServerJobs serverJob = new UserCode.ServerJobs(this.DataWorkspace.ApplicationData);
            serverJob.StartServerJob(entity);
        }

        partial void tbServerJobSet_Updated(tbServerJob entity)
        {
            if (!entity.IsReady)
                return;

            if (entity.tlJobStatus != null && entity.tlJobStatus.StaticId == 3)     // Completed
                return;

            if (entity.Name == "FirstInit")     // Needs special Treatment - again
                return;

            UserCode.ServerJobs serverJob = new UserCode.ServerJobs(this.DataWorkspace.ApplicationData);
            serverJob.StartServerJob(entity);
        }

        partial void tbTrainsessionSet_Inserted(tbTrainsession entity)
        {
            // after a new Trainsession is created, let's add the corresponding Stakeholder
            ApplicationDataService appData = this.DataWorkspace.ApplicationData;

            IEnumerable<tlCustomPropertyChoices> query = (from s in appData.tlCustomPropertyChoicesSet
                                                          where s.StaticId == 6
                                                             && s.tlCustomProperty.StaticId == 3
                                                          select s).Execute();
            tlCustomPropertyChoices avaiable = query.FirstOrDefault();  // "Anwesend"

            using (SqlConnection connection = new SqlConnection())
            {
                // Todo: Find a way to get the connectionStingName - not just guessing it right.
                string connectionStringName = "_IntrinsicData"; //Maybe this won't work in deployed app
                connection.ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

                string procedure = "dbo.spGetRecentAttendance";

                foreach (trTraingroupStakeholder stakeholder in entity.tlTraingroup.trTraingroupStakeholder)
                {
                    if (stakeholder.tbStakeholder.IsDeleted)    // Ignore deleted Stakeholder
                        continue;

                    trStakeholderTrainsession newStakeholder = appData.trStakeholderTrainsessionSet.AddNew();
                    newStakeholder.tbTrainsession = entity;
                    newStakeholder.tbStakeholder = stakeholder.tbStakeholder;
                    newStakeholder.AttendanceStatus = avaiable;
                    newStakeholder.AttendanceType = stakeholder.AttendanceType;
                    newStakeholder.Checked = false;

                    string recentAttendance = "";
                    using (SqlCommand command = new SqlCommand(procedure, connection))  // Fire StoredProcedure
                    {
                        command.CommandType = CommandType.StoredProcedure;

                        command.Parameters.Add(new SqlParameter("@TraingroupId", entity.tlTraingroup.Id));
                        command.Parameters.Add(new SqlParameter("@StakeholderId", stakeholder.tbStakeholder.Id));

                        SqlDataAdapter dataAdapter = new SqlDataAdapter(command);

                        DataSet dataSet = new DataSet();
                        dataAdapter.Fill(dataSet, "result");

                        DataTable dataTable = dataSet.Tables["result"];

                        if (dataTable.Rows.Count <= 0)
                        {
                            recentAttendance = "-----";
                            continue;
                        }

                        foreach (DataRow row in dataTable.Rows)
                        {
                            recentAttendance += row["ShortStatus"];
                        }
                    }
                    newStakeholder.RecentAttendance = recentAttendance;
                }
            }
        }

        partial void tlCustomPropertySet_Validate(tlCustomProperty entity, EntitySetValidationResultsBuilder results)
        {
            // Update
            if (entity.Details.EntityState == Microsoft.LightSwitch.EntityState.Modified)
            {
                if (entity.IsBoundStatically != entity.Details.Properties.IsBoundStatically.OriginalValue)
                    results.AddEntityError("Changing IsBoundStatically is not allowed");
                else
                {
                    if (!entity.IsBoundStatically)
                    {
                        if (entity.IsChooseable != entity.Details.Properties.IsChooseable.OriginalValue)
                            foreach (tlCustomPropertyChoices choice in entity.tlCustomPropertyChoicesSetItem)
                                choice.Delete();

                        if (entity.IsChooseable == false)
                            foreach (tlCustomPropertyChoices choice in entity.tlCustomPropertyChoicesSetItem)
                                choice.Delete();
                    }
                    else
                    {
                        if (entity.IsChooseable != entity.Details.Properties.IsChooseable.OriginalValue)
                            results.AddEntityError("IsChooseable can't be changed when IsBoundStatically is set.");
                    }
                }
            }

            // Delete
            if (entity.Details.EntityState == Microsoft.LightSwitch.EntityState.Deleted)
                if (entity.IsBoundStatically)
                    results.AddEntityError("Deleting property with IsBoundStatically set to true is not allowed");
        }

        partial void tlCustomPropertySet_Deleting(tlCustomProperty entity)
        {
            entity.Details.ValidationResults.Any(); //just called to make sure validation logic is triggered
        }

        partial void tlCustomPropertyChoicesSet_Deleting(tlCustomPropertyChoices entity)
        {
            entity.Details.ValidationResults.Any(); //just called to make sure validation logic is triggered
        }

        partial void tlCustomPropertyChoicesSet_Validate(tlCustomPropertyChoices entity, EntitySetValidationResultsBuilder results)
        {
            // Update
            if (entity.Details.EntityState == Microsoft.LightSwitch.EntityState.Modified)
            {
                if (entity.IsBoundStatically != entity.Details.Properties.IsBoundStatically.OriginalValue)
                    results.AddEntityError("Changing choosing with IsBoundStatically set to true is not allowed");
            }

            // Delete
            if (entity.Details.EntityState == Microsoft.LightSwitch.EntityState.Deleted)
            {
                if (entity.IsBoundStatically)
                    results.AddEntityError("Deleting choosing with IsBoundStatically set to true is not allowed");
            }
        }
    }
}